const {jwtAdminRouter} = require('../../util')
const {query} = require('../../db')
let router = jwtAdminRouter()

const tableName = 'gifts'

router.get('/', async (req, res, next)=>{
    let page = req.query.page || 1
    let pageSize = req.query.page_size || 20

    let offset = (page-1)*pageSize
    let sql = `SELECT * FROM ${tableName} ORDER BY id DESC LIMIT ${offset},${pageSize}`

    let data = await query(sql).catch(next)
    if(data === undefined) return

    let total = await query(`SELECT COUNT(*) total FROM ${tableName}`).catch(next)
    if(total === undefined) return

    res.json({
        'ok': 1,
        'total': total[0].total,
        data
    })
})

router.post('/', async (req, res, next)=>{
    let gift_name = req.body.gift_name
    let gift_icon = req.body.gift_icon
    let price = req.body.price

    let data = {
        gift_name,
        gift_icon,
        price
    }

    let sql = `INSERT INTO ${tableName} SET ?`
    let ret = await query(sql, data).catch(next)
    if(ret === undefined) return 

    res.json({
        'ok': 1
    })
})

router.put('/:id', async (req, res, next)=>{
    let gift_name = req.body.gift_name
    let gift_icon = req.body.gift_icon
    let price = req.body.price
    let id = req.params.id
    
    let data = {
        gift_name,
        gift_icon,
        price
    }

    let sql = `UPDATE ${tableName} SET ? WHERE id = ?`
    let ret = await query(sql, [data, id]).catch(next)
    if(ret === undefined) return 

    res.json({
        'ok': 1
    })
})

router.delete('/:id', async (req, res, next)=>{
    let id = req.params.id

    let sql = `DELETE FROM ${tableName} WHERE id = ?`
    let ret = await query(sql, id).catch(next)
    if(ret === undefined) return 

    res.json({
        'ok': 1
    })
})

router.get('/:id', async (req, res, next)=>{
    let id = req.params.id

    let sql = `SELECT * FROM ${tableName} WHERE id = ?`
    let ret = await query(sql, id).catch(next)
    if(ret === undefined) return 

    res.json({
        'ok': 1,
        'data': ret[0]
    })
})

module.exports = router